<?php
class Model_Role{
	
	public static $resources;
	
	public static function setRoles(){
		
		$data=new Model_AuthItem();
		
		$data->addNewDeniedByAction("dish", "create", "guest");
		$data->addNewDeniedByAction("location", "index", "guest");
		$data->addNewDeniedByAction("location", "detail", "guest");
		
		//$data->addNewDeniedByController("dish", "guest");
		
		Model_Role::$resources=$data;
	}
	
	public static function getCurrentRole(){
		$auth = Zend_Auth::getInstance ();
		$isLoggedIn = false;
		$user = '';
		if ($auth->hasIdentity ()) {
			$user = $auth->getIdentity ();
			if ($user=="admin") return "admin";
			if (Model_Role::startsWith($user, "emp")) return "employee";
			return "customer";		
		}
		else
		{
			return "guest";
		}
	}
	
	//thao tac chuoi
	public static function startsWith($haystack,$needle,$case=true) {
		if($case){return (strcmp(substr($haystack, 0, strlen($needle)),$needle)===0);}
		return (strcasecmp(substr($haystack, 0, strlen($needle)),$needle)===0);
	}
	
	static function endsWith($haystack,$needle,$case=true) {
		if($case){return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);}
		return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);
	}
	
	public static function IsDenied(){
		$controller=Zend_Controller_Front::getInstance()->getRequest()->getControllerName();
		$action=Zend_Controller_Front::getInstance()->getRequest()->getActionName();
		$role=Model_Role::getCurrentRole();
		foreach (Model_Role::$resources->deniedByController as $r){
			$c=$r[0];
			$ro=$r[1];
			if ($controller==$c && $role==$ro ){
				return true;
			}
		}
		foreach (Model_Role::$resources->deniedByAction as $r){
			$c=$r[0];
			$ro=$r[2];
			$a=$r[1];
			if ($controller==$c && $role==$ro && $a==$action ){
				return true;
			}
		}
		return false;
	}
}

